<?php

namespace app\adminapi\service;

use app\adminapi\model\sysnotice\SysNoticeDO;
use app\common\exception\OtherException;

class SysNoticeService
{
    public function list(array $param): array
    {
        $where = [];
        if (isset($param['noticeTitle'])) {
            $where[] = ['notice_title', 'like', '%' . $param['noticeTitle'] . '%'];
        }
        if (isset($param['noticeType'])) {
            $where[] = ['notice_type', '=', $param['noticeType']];
        }
        if (isset($param['status'])) {
            $where[] = ['status', '=', $param['status']];
        }
        if (isset($param['timeArr'])) {
            $where[] = ['create_time', 'between', $param['timeArr']];
        }
        $paginate['list_rows'] = $param['pageSize'];
        if (!empty($param['pageNo'])) {
            $paginate['page'] = $param['pageNo'];
        }
        $result = (new SysNoticeDO())
            ->where($where)
            ->paginate($paginate)
            ->toArray();
        return [
            'total' => $result['total'],
            'list' => $result['data']
        ];
    }

    public function addSysNotice(array $sysNoticeDO)
    {
        return SysNoticeDO::create($sysNoticeDO);
    }

    public function deleteSysNotice(int $noticeId)
    {
        $this->validSysNoticeExist($noticeId);
        return SysNoticeDO::destroy($noticeId);
    }

    public function updateSysNotice(array $sysNoticeDO)
    {
        $this->validSysNoticeExist($sysNoticeDO['noticeId']);
        return SysNoticeDO::update($sysNoticeDO);
    }

    public function getSysNotice(int $noticeId)
    {
        return SysNoticeDO::find($noticeId);
    }

    public function validSysNoticeExist(int $noticeId)
    {
        $exist = SysNoticeDO::find($noticeId);
        if (empty($exist)) {
            throw new OtherException('$exist');
        }
    }
}